package com.wjzjq.hiring.talent.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.wjzjq.hiring.common.PageModel;
import com.wjzjq.hiring.common.util.AppUtil;
import com.wjzjq.hiring.company.dao.ApplicationDao;
import com.wjzjq.hiring.company.entity.ApplicationEntity;
import com.wjzjq.hiring.talent.dao.ResumeDao;
import com.wjzjq.hiring.talent.dao.TalentDao;
import com.wjzjq.hiring.talent.entity.ResumeEntity;
import com.wjzjq.hiring.talent.entity.TalentEntity;

@WebServlet("/TalentServlet")
public class TalentServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private TalentDao talentDao = new TalentDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 解决POST请求的乱码问题
		request.setCharacterEncoding("UTF-8");
		// 获取command 来注销或者 登录
		String command = request.getParameter("command");
		if ("login".equals(command)) {
			this.login(request, response);
		} else if ("logout".equals(command)) {
			this.logout(request, response);
		} else if ("register".equals(command)) {
			this.register(request, response);
		} else if ("updateTalent".equals(command)) {
			this.updateTalent(request, response);
		}else if ("updatePassword".equals(command)) {
				this.updatePassword(request, response);
		} else if ("main".equals(command)) {
			this.main(request, response);
		} else {
			new RuntimeException("非法的哦");
		}
	}
	
	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String oldpassword = request.getParameter("oldPassword");
		String newpassword = request.getParameter("newPassword");
		String repassword = request.getParameter("rePassword");
		System.out.println(newpassword);
		System.out.println(repassword);
		TalentEntity talentE = (TalentEntity) request.getSession()
				.getAttribute("talent");
		String password = talentE.getPassword();

		if (oldpassword.equals(password)) {
			if (newpassword.equals(repassword)) {
				TalentEntity talent = new TalentEntity();
				talent.setPassword(repassword);
				talent.setCode(talentE.getCode());
				talent.setName(talentE.getName());
				talent.setPhone(talentE.getPhone());
				talent.setEmail(talentE.getEmail());
				talent.setAge(talentE.getAge());
				talent.setGender(talentE.getGender());
				talent.setHobby(talentE.getHobby());
				talent.setId(talentE.getId());
				int row = talentDao.update(talent);
				if (row == 1) {
					System.out.println("success");
					request.getSession().setAttribute("talent", talent);
					response.sendRedirect(request.getContextPath()
							+ "/view/talent/talent-updatePassword.jsp?updateSuccess=true");
				} else {
					System.out.println("failed");
					response.sendRedirect(request.getContextPath()
							+ "/view/talent/talent-updatePassword.jsp?updateError=true");
				}
			} else {
				response.sendRedirect(request.getContextPath()
						+ "/view/talent/talent-updatePassword.jsp?repasswordError=true");
			}
		} else {
			response.sendRedirect(request.getContextPath()
					+ "/view/talent/talent-updatePassword.jsp?oldpasswordError=true");
		}
	}

	/**
	 * 更新个人资料
	 */
	private void updateTalent(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 从session里拿到id
		TalentEntity talentE = (TalentEntity) request.getSession().getAttribute("talent");
		int id = talentE.getId();
		// 从页面上拿到更改的属性
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		int gender = Integer.valueOf(request.getParameter("gender"));
		int age = Integer.valueOf(request.getParameter("age"));
		String[] hobbies = request.getParameterValues("hobby");// 兴趣很多项还是checkbox用字符串数组接收
		TalentEntity talent = new TalentEntity();
		talent.setAge(age);
		talent.setEmail(email);
		talent.setGender(gender);
		talent.setName(name);
		talent.setPassword(password);
		talent.setPhone(phone);
		talent.setPhone(phone);
		talent.setId(id);
		if (hobbies != null) {
			talent.setHobby(StringUtils.join(hobbies, "|"));// 工具类将数组用|间隔拼成字符串
		} else {
			talent.setHobby("");
		}
		int row = talentDao.update(talent);
		if (row == 1) {
			// 若成功 要更新session 直接覆盖以前的属性
			talent.setCode(talentE.getCode());
			request.getSession().setAttribute("talent", talent);
			response.sendRedirect(request.getContextPath() + "/view/talent/talent-info.jsp?updateSuccess=true");
		} else {
			response.sendRedirect(request.getContextPath() + "/view/talent/talent-info.jsp?updateError=true");

		}

	}

	/**
	 * 登录
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1、接收参数
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String remember = request.getParameter("remember");
		if ("true".equals(remember)) {
			// 创建cookie对象 并且避免中文乱码
			Cookie codeCookie = new Cookie("code", URLEncoder.encode(code, "utf-8"));
			// 如果没有设置存活时间，cookie在浏览器关闭时就会失效，也不会存入硬盘
			codeCookie.setMaxAge(60 * 30);
			// 在response里添加cookie 一共存三个 用户名 密码 和打勾
			response.addCookie(codeCookie);

			Cookie passwordCookie = new Cookie("password", password);
			passwordCookie.setMaxAge(60 * 30);
			response.addCookie(passwordCookie);

			Cookie rememberCookie = new Cookie("remember", remember);
			rememberCookie.setMaxAge(60 * 30);
			response.addCookie(rememberCookie);
		}
		TalentEntity talent = null;
		talent = talentDao.login(code, password);
		System.out.println(talent);
		if (talent != null) {
			// 只能有一个登陆
			request.getSession().removeAttribute("company");
			request.getSession().setAttribute("talent", talent);
			response.sendRedirect("TalentServlet?command=main");// 为了直接跳地址栏 不让后退
		} else {
			// 登录失败
			response.sendRedirect("view/talent/login.jsp?loginError=true");

		}
	}

	/**
	 * 专门用来发送 简历信息列表的方法 <br>
	 * 刷新时 若发现session里的talent没有了 就去Login界面
	 * 
	 */
	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<ResumeEntity> resumeList = ResumeDao.getResumeList(AppUtil.getTalentId(request));
		int pageNum = 1;
		int pageSum = 10;
		String pn = request.getParameter("pageNum");
		String ps = request.getParameter("pageSum");
		if (pn != null) {
			pageNum = Integer.valueOf(pn);
		}
		if (ps != null) {
			pageSum = Integer.valueOf(ps);
		}
		PageModel<ApplicationEntity> pageModel = ApplicationDao.getAppList(AppUtil.getTalentId(request), pageNum,
				pageSum);
		request.setAttribute("resumeList", resumeList);
		request.setAttribute("pageModel", pageModel);
		request.getRequestDispatcher("view/talent/main.jsp").forward(request, response);

	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();// session失效 实现注销
		response.sendRedirect("view/company/position-list.jsp?logoutSuccess=true");
	}

	private void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收参数
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		int gender = Integer.valueOf(request.getParameter("gender"));
		int age = Integer.valueOf(request.getParameter("age"));
		String[] hobbies = request.getParameterValues("hobby");// 兴趣很多项还是checkbox用字符串数组接收
		TalentEntity talent = new TalentEntity();
		talent.setAge(age);
		talent.setCode(code);
		talent.setEmail(email);
		talent.setGender(gender);
		talent.setName(name);
		talent.setPassword(password);
		talent.setPhone(phone);
		StringBuilder sb = new StringBuilder();
		if (hobbies != null) {
			sb.append(StringUtils.join(hobbies, "|"));
		}
		talent.setHobby(sb.toString());
		if (talentDao.register(talent) != 0) {
			request.setAttribute("register", "注册成功请你登录");
			request.getRequestDispatcher("view/talent/login.jsp?registerSuccess=true").forward(request, response);;// 注册成功去登陆页面
		} else {
			request.setAttribute("talent", talent);
			request.getRequestDispatcher("view/talent/register.jsp").forward(request, response);
		}

	}

}
